import FormHook from "@/hook/formHook";
import { message } from "ant-design-vue";
import { addCustomerApi, editCustomerApi, resetPasswordApi } from "@/api/managementCenter/customerManagement";
import type { Rule } from "ant-design-vue/es/form";
import PermissionStore from "@/store/modules/permission";
export default function OperationHook(state: Base.GeneraDataType) {
  const { formDataRef, formState, emit, passData, type } = state;
  const { resetFields, validateZhInputHandle, filterOption, validatePhoneInputHandle } = FormHook({ formState });
  const onFinish = () => {
    let requestFn;
    const params = {
      ...formState
      // address: formState.address.join("/")
    };
    if (type.value === 1) {
      requestFn = addCustomerApi;
    } else {
      requestFn = editCustomerApi;
      params.id = passData.value.id;
    }
    requestFn(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("操作成功!");
        emit("submit");
      }
    });
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };
  const addContactHandle = () => {
    formState.contactList.push({
      name: undefined,
      phone: undefined,
      address: undefined,
      email: undefined
    });
  };
  const deleteContactHandle = (rowIndex: number) => {
    formState.contactList.splice(rowIndex, 1);
  };
  const changeAccountName = (v: any) => {
    formState.accountName = v.target.value;
  };

  const validatePhone = (_rule: Rule, value: string) => {
    const str = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/;
    if (!value || value.length < 11) {
      return Promise.reject(new Error("最少11位数手机号!"));
    } else if (!str.test(value)) {
      return Promise.reject(new Error("请输入正确的手机号格式"));
    } else {
      return Promise.resolve();
    }
  };
  //重置密码
  const resetPasswordHandle = () => {
    return resetPasswordApi({ id: formState.companyId, password: PermissionStore.userInfo.password }).then((res: any) => {
      console.log(res);
    });
  };

  return {
    onFinishFailed,
    resetHandle,
    onFinish,
    resetFields,
    validateZhInputHandle,
    addContactHandle,
    deleteContactHandle,
    filterOption,
    changeAccountName,
    validatePhoneInputHandle,
    validatePhone,
    resetPasswordHandle
  };
}
